package cn.htsyb.synergy.security.entity;

import cn.htsyb.synergy.orm.jpa.model.entity.AbsStructureEntity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.Formula;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;

import java.util.List;

/**
 * 组织 实体类
 * @author lakeside hubin_yuan.410@hotmail.com
 * @version V1.0.0
 * @date 2022/5/23
 * @since 1.0
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@Setter
@Getter
@NoArgsConstructor
@DynamicInsert
@Entity(name = "SecurityOrganize")
@Table(name = "security_organize")
@org.hibernate.annotations.Table(appliesTo = "security_organize", comment = "组织")
@Schema(description = "组织")
public class SecurityOrganize extends AbsStructureEntity {
    private static final long serialVersionUID = 1L;
    /**
     * 领导者
     */
    @Column(name = "leader_id", length = 36, columnDefinition = " VARCHAR(36) COMMENT '领导者' ")
    @Schema(name = "leaderId", description = "领导者")
    protected String leaderId;
    /**
     * 管理者
     */
    @Column(name = "manager_id", length = 36, columnDefinition = " VARCHAR(36) COMMENT '管理者' ")
    @Schema(name = "managerId", description = "管理者")
    protected String managerId;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @OneToMany(fetch = FetchType.LAZY)
    @NotFound(action = NotFoundAction.IGNORE)//允许映射对象为空
    @JoinColumn(name = "organize_id"
            , nullable = false, insertable = false, updatable = false//字段可为空；更新不写入；修改不写入
            , foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT))//不建立外键
    protected List<SecurityUser> users;

    @Transient
    @Schema(name = "hasOrganize", description = "是否组织")
    protected Boolean hasOrganize = true;

    /**
     * 子级用户量
     */
    @Schema(name = "subUserSize", description = "子级用户量")
    @Formula("(select count(1) from security_user hu where hu.organize_id=id_)")
    protected Integer subUserSize;
    /**
     * 领导者回显
     */
    @Schema(name = "leaderIdName", description = "领导者回显")
    @Formula("(select hu.real_name from security_user hu where hu.id_=leader_id)")
    protected String leaderIdName;
    /**
     * 管理者回显
     */
    @Formula("(select hu.real_name from security_user hu where hu.id_=manager_id)")
    @Schema(name = "managerIdName", description = "管理者回显")
    protected String managerIdName;
    /**
     * 上级组织回显
     */
    @Formula("(select ho.name_ from security_organize ho where ho.id_=parent_id)")
    @Schema(name = "parentIdName", description = "上级组织回显")
    protected String parentIdName;

}